package com.sz.netty.util;

import java.util.Arrays;

public class PacketAnalyzer {
    
    public static void main(String[] args) {
        // Sample data packets
        String[] packets = {
            "7B7B7B88353130303034003B027601190A1C0E26237B0906E931313433312E3638383334333830342E3532383338000000850930312E308B7D7D7D",
            "7B7B7B88353130303034003B027701190A1C0E26267C0905DB31313433312E3638383337333830342E3532383433000000850930312E30B67D7D7D",
            "7B7B7B88353130303034003B027801190A1C0E26297D0905C131313433312E3638383432333830342E3532383438000000850930312E30A47D7D7D",
            "7B7B7B88353130303034003B027901190A1C0E262C7E09071C31313433312E3638383436333830342E3532383533000000850930312E30727D7D7D",
            "7B7B7B88353130303034003B027A01190A1C0E262F7F09042831313433312E3638383739333830342E3532383439000000850930312E30437D7D7D"
        };
        
        System.out.println("Analyzing radar distance from sample packets:");
        System.out.println("==============================================");
        
        for (int i = 0; i < packets.length; i++) {
            byte[] packet = hexStringToByteArray(packets[i]);
            System.out.println("Packet " + (i + 1) + ":");
            System.out.println("  Hex: " + packets[i]);
            
            // Extract radar distance (2 bytes at offset 11-12 from content start)
            // Content starts after: header(3) + type(1) + deviceId(6) + packetLength(2) = 12 bytes
            // Then command byte(1) + dataCount(1) + recordIndex(1) = 3 bytes
            // So radar distance is at offset 12 + 3 + 8 = 23 bytes from packet start
            // Or offset 8-9 from record start (after time(6) + randTime(1) + status(1))
            
            if (packet.length > 24) {
                int radarDistance = ((packet[23] & 0xFF) << 8) | (packet[24] & 0xFF);
                System.out.println("  Radar Distance: " + radarDistance + " mm");
                
                // Also extract timestamp for reference
                if (packet.length > 18) {
                    System.out.print("  Timestamp bytes: ");
                    for (int j = 12; j < 18; j++) {
                        System.out.print(String.format("%02X ", packet[j] & 0xFF));
                    }
                    System.out.println();
                }
            }
            System.out.println();
        }
    }
    
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}